<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane v-for="item in tabsList" :key="item.id" :label="item.label" :name="item.name" />
    </el-tabs>
    <div class="material-add">
      <div class="material-search" />
      <div class="material-button">
        <el-button type="primary" @click="showAddForm">上传素材</el-button>
      </div>
    </div>
    <el-table :data="tableData" v-loading="tableLoading">
      <el-table-column label="序号" type="index" :index="indexMethod" />
      <el-table-column prop="id" label="素材ID" />
      <el-table-column prop="effectiveTime" label="生效时间" />
      <el-table-column prop="uploadUser" label="上传人" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag :type="activeStatus[scope.row.status].color">{{ activeStatus[scope.row.status].text }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-switch style="margin-right:10px;" :value="scope.row.status" :active-value="1" :inactive-value="0"
            @change="($event) => handleStatus($event, scope.row)">
          </el-switch>
          <el-button @click="materialItemClick(scope.row)" type="text" size="small">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <InBody v-show="total > 0">
      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getTableData" />
    </InBody>
    <el-dialog title="配置" :visible.sync="dialogVisible" width="600px" @close="closeAddForm">
      <el-form :model="addForm" :rules="rules" label-position="right" label-width="100px" ref="addForm"
        :disabled="editDisabled">
        <el-form-item label="生效时间" prop="effectiveTime">
          <el-date-picker v-model="addForm.effectiveTime" :picker-options="{ disabledDate }" type="datetime"
            placeholder="生效时间" />
        </el-form-item>
        <el-form-item label="图片" prop="imagesUrl" v-if="activeName !== 'cooperate'">
          <el-upload class="file-uploader" :action="`${baseUrl}/file/upload`" :show-file-list="false"
            accept=".png,.jpg,.jpeg" :on-success="handleFileSuccess">
            <img v-if="addForm.imagesUrl" :src="addForm.imagesUrl" class="file">
            <i v-else class="el-icon-plus file-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="图片" prop="fileList" v-else>
          <el-upload class="file-uploader" :action="`${baseUrl}/file/upload`" multiple list-type="picture-card"
            accept=".png,.jpg,.jpeg" :on-success="handleFileListSuccess" :before-remove="(file) => { removeImg(file) }"
            :file-list="addForm.fileList">
            <i class="el-icon-plus file-uploader-icon" />
          </el-upload>
        </el-form-item>
        <template v-if="activeName === 'team'">
          <el-form-item label="宠物名称" prop="contentName">
            <el-input v-model="addForm.contentName" placeholder="请输入宠物名称" :maxlength="5" />
          </el-form-item>
          <el-form-item label="品种" prop="contentKind">
            <el-input v-model="addForm.contentKind" placeholder="请输入宠物品种" :maxlength="10" />
          </el-form-item>
          <el-form-item label="性格" prop="contentCharacter">
            <el-input v-model="addForm.contentCharacter" placeholder="请输入宠物性格" :maxlength="10" />
          </el-form-item>
          <el-form-item label="地址" prop="contentAddress">
            <el-input v-model="addForm.contentAddress" placeholder="请输入宠物地址" :maxlength="5" />
          </el-form-item>
          <el-form-item label="领养人" prop="contentReceiver">
            <el-input v-model="addForm.contentReceiver" placeholder="请输入宠物领养人" :maxlength="20" />
          </el-form-item>
        </template>
        <template v-if="activeName === 'authority'">
          <el-form-item label="职称" prop="contentKind">
            <el-input v-model="addForm.contentKind" placeholder="请输入职称" :maxlength="10" />
          </el-form-item>
          <el-form-item label="研究方向" prop="contentCharacter">
            <el-input v-model="addForm.contentCharacter" placeholder="请输入研究方向" :maxlength="10" />
          </el-form-item>
          <el-form-item label="推荐语" prop="contentRecommend">
            <el-input v-model="addForm.contentRecommend" placeholder="请输入推荐语" :maxlength="100" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForm">取消</el-button>
        <el-button type="primary" @click="handleSubmit" v-if="!editDisabled">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { queryMaterialList, saveMaterial, updateMaterial } from '@/api/material';
import moment from 'moment';
import { pick } from "lodash";
import { getBaseUrl } from "@/utils";

export default {
  computed: {
    ...mapGetters(['name']),
  },
  data() {
    return {
      tabsList: [
        { id: 8, label: "心声-合作机构", name: "cooperate" },
        { id: 9, label: "心声-毛球小队", name: "team" },
        { id: 10, label: "心声-专业资质", name: "flair" },
        { id: 11, label: "心声-权威推荐", name: "authority" },
        { id: 12, label: "心声-用户案例", name: "case" }
      ],
      activeName: 'cooperate',
      tableData: [],
      tableLoading: false,
      baseUrl: getBaseUrl(),
      dialogVisible: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      editDisabled: false,
      addForm: {
        effectiveTime: '',
        contentKind: '',
        contentCharacter: '',
        contentAddress: '',
        contentReceiver: '',
        contentRecommend: '',
        imagesUrl: '',
        fileList: [],
      },
      rules: {
        effectiveTime: [{ required: true, message: '请设置生效时间', trigger: 'blur' }],
        contentName: [{ required: true, message: '请输入宠物名字', trigger: 'blur' }],
        contentKind: [{ required: true, message: '请输入宠物品种', trigger: 'blur' }],
        contentCharacter: [{ required: true, message: '请输入宠物性格', trigger: 'blur' }],
        contentAddress: [{ required: true, message: '请输入宠物地址', trigger: 'blur' }],
        contentReceiver: [{ required: true, message: '请输入宠物领养人', trigger: 'blur' }],
        contentRecommend: [{ required: true, message: '请输入权威机构-推荐语', trigger: 'blur' }],
        imagesUrl: [{ required: true, message: '请上传文件', trigger: 'blur' }],
        fileList: [{ required: true, message: '请上传文件', trigger: 'blur' }],
      },
      activeStatus: [
        { color: '', text: '待生效' },
        { color: 'success', text: '生效中' },
        { color: 'warning', text: '已下线' },
      ],
    };
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    disabledDate(date) {
      return moment().isAfter(date, 'second')
    },
    handleStatus(event, item) {
      this.$confirm(`确认要${event === 0 ? '上线' : '下线'}吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        updateMaterial({ status: event, id: item.id }).then(res => {
          if (res.code === 200) {
            this.$message({ message: '操作成功', type: 'success' });
            this.getTableData()
          }
        })
      }).catch(() => { })
    },
    indexMethod(index) {
      return index + 1;
    },
    showContentLabel() {
      const current = this.tabsList.find(item => item.name === this.activeName);
      return current.label
    },
    async getTableData() {
      this.tableLoading = true
      const tab = this.tabsList.find(item => item.name === this.activeName);
      if (!tab) return;
      const { code, rows, total } = await queryMaterialList({ type: tab.id, ...this.queryParams })
      if (code !== 200) return;
      this.total = +total
      this.tableData = (rows || []).map(item => {
        item.effectiveTime = moment(item.effectiveTime).format('YYYY-MM-DD HH:mm:ss')
        return item
      })
      this.tableLoading = false
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
      this.queryParams = { pageNum: 1, pageSize: 10 }
      this.getTableData()
    },
    materialItemClick(record) {
      const newRecord = JSON.parse(JSON.stringify(record));
      if (this.activeName === 'cooperate') {
        const imageList = record.imagesUrl.split(';');
        const newList = [];
        imageList.map(item => {
          const urlObj = new URL(item);
          const fileName = urlObj.pathname.split('/').pop();
          newList.push({
            uid: Date.now().toString(36) + Math.random().toString(36).substring(2),
            name: fileName,
            url: item
          })
        })
        newRecord.fileList = newList;
      }
      this.addForm = pick(newRecord, Object.keys(this.addForm));
      this.editDisabled = true
      this.dialogVisible = true
    },
    resetFields() {
      Object.assign(this.$data.addForm, this.$options.data().addForm)
    },
    showAddForm() {
      this.resetFields()
      this.dialogVisible = true
    },
    closeAddForm() {
      this.dialogVisible = false;
      this.editDisabled = false;
      this.editId = ''
      this.resetFields();
    },
    handleFileSuccess({ code, data }, file) {
      if (code !== 200) return;
      const isImage = ["png", "jpg", "jpeg"].some(v => file.raw.type.includes(v))
      const isVideo = ["mp4", "3gp", 'm3u8'].some(v => file.raw.type.includes(v))
      if (isImage) {
        this.addForm.urlType = 0
        this.addForm.imagesUrl = data.url
      }
      if (isVideo) {
        this.addForm.urlType = 1
        this.addForm.videoUrl = data.url
      }
    },
    handleFileListSuccess({ code, data }, file) {
      if (code !== 200) return;
      const isImage = ["png", "jpg", "jpeg"].some(v => file.raw.type.includes(v))
      if (isImage) {
        this.addForm.urlType = 0;
        const urlObj = new URL(data.url);
        const fileName = urlObj.pathname.split('/').pop();
        this.addForm.fileList.push({
          uid: Date.now().toString(36) + Math.random().toString(36).substring(2),
          name: fileName,
          url: data.url
        });
      }
    },
    removeImg(file) {
      const fileIndex = this.addForm.fileList.findIndex(item => item.name === file.name);
      this.addForm.fileList.splice(fileIndex, 1)
    },
    handleSubmit() {
      const current = this.tabsList.find(item => item.name === this.activeName);
      this.$refs['addForm'].validate(async (valid) => {
        if (!valid) return;
        const params = JSON.parse(JSON.stringify({ ...this.addForm }));
        const plusParams = { type: current.id, name: current.label };
        const effectiveTime = moment(this.addForm.effectiveTime).format('YYYY-MM-DD HH:mm:ss');
        if (this.activeName === 'cooperate') {
          const urls = params.fileList.map(item => item.url);
          params.imagesUrl = urls.join(';');
          delete params.fileList;
        }
        const { code } = await saveMaterial([{ ...params, ...plusParams, effectiveTime, uploadUser: this.name }])
        if (code !== 200) return;
        this.$message({ message: '添加成功', type: 'success' });
        this.closeAddForm();
        return this.getTableData();
      })
    }
  }
};
</script>
<style scoped lang="scss">
.material-add {
  width: 100%;
  height: auto;
  display: grid;
  grid-template-columns: 50% 50%;
  margin-bottom: 15px;

  div {
    &.material-search {}

    &.material-button {
      text-align: right;
    }
  }
}

.file-uploader {
  &::v-deep .el-upload {
    width: 150px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409EFF;
    }

  }

  .file-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .file {
    width: 148px;
    height: 148px;
    display: block;
  }
}
</style>
